package jdbc.dao;

import jdbc.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//定义常用操作
public interface StudentDao {
    int add(Student stu);

    int update(Student stu);

    int del(Student stu);

    int del(long stuno);

    /**
     * 主键,查找单个对象
     */

    public default Student get(long stuno) {
        Connection con = DbUtil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = con.prepareStatement("select * from s_student where stuno=?");
            ps.setLong(1, stuno);
            rs = ps.executeQuery();
            if (rs.next()) {
                Student stu = new Student();
                stu.setStuno(rs.getLong("stuno"));
                stu.setSname(rs.getString("sname"));
                stu.setQq(rs.getString("qq"));
                stu.setWechat(rs.getString("wechat"));
                stu.setTelephone(rs.getString("telephone"));
                stu.setEnterdate(rs.getDate("enterdate"));
                stu.setBirthday(rs.getDate("birthday"));
                stu.setGradeid(rs.getLong("gradeid"));
                //待完善
                return stu;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtil.closeResources(con, ps, rs);
        }
        return null;
    }

    //多个对象
    //加上姓名作为模糊查找条件
    default List<Student> search(int pageNo, int pageSize, String sname) {
        List<Student> data = new ArrayList<>();
        Connection con = DbUtil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String sql = "select * from s_student where sname like ? limit ?,?";
            ps = con.prepareStatement(sql);
            ps.setInt(2, (pageNo - 1) * pageSize);
            ps.setInt(3, pageSize);
            ps.setString(1, "%" + sname + "%");
            rs = ps.executeQuery();
            while (rs.next()) {
                Student stu = new Student();
                stu.setStuno(rs.getLong("stuno"));
                stu.setSname(rs.getString("sname"));
                stu.setQq(rs.getString("qq"));
                stu.setWechat(rs.getString("wechat"));
                stu.setTelephone(rs.getString("telephone"));
                stu.setEnterdate(rs.getDate("enterdate"));
                stu.setBirthday(rs.getDate("birthday"));
                stu.setGradeid(rs.getLong("gradeid"));
                //待完善
                data.add(stu);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtil.closeResources(con, ps, rs);
        }
        return data;
    }
}
